<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <!-- 以下为原有查询条件 -->
      <el-form-item :label="t('article.title')">
        <el-input
          v-model="form.keywords"
          clearable
          :placeholder="t('article.titleSearchMsg')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('article.type')" prop="type">
        <el-select
          v-model="form.type"
          :filterable="true"
          :placeholder="t('article.type')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('article.category')" prop="category">
        <el-select
          v-model="form.category"
          :filterable="true"
          :placeholder="t('article.category')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增：日期区间筛选控件（开始） -->
      <el-form-item :label="t('article.create_time')">
        <el-date-picker
          v-model="form.create_time"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          value-format="YYYY-MM-DD"
          style="width: 380px"
        />
      </el-form-item>
      <!-- 新增：日期区间筛选控件（结束） -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">{{
          t('common.search')
        }}</el-button>
        <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd">
        {{ t('article.add') }}
      </el-button>
      <el-button type="danger" @click="handleDelete('Bulk', {})">
        {{ t('article.del') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('common.serialNumber')" prop="id" min-width="80" />
      <el-table-column :label="t('article.title')" prop="title" min-width="120" />
      <el-table-column :label="t('article.photo')" min-width="100">
        <template #default="{ row }">
          <el-avatar v-if="row.photoId" :src="row.photoUrl" :size="40" />
          <el-avatar v-else :size="40" icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column :label="t('article.type')" prop="type" min-width="120">
        <template #default="{ row }">
          {{ useEnumeratePicker(typeList, row.type) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('article.publish_date')"
        prop="publish_date"
        min-width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('article.category')"
        min-width="100"
        prop="category"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(categoryList, row.category) }}
        </template>
      </el-table-column>
      <el-table-column :label="t('article.create_time')" prop="create_time" min-width="180" />
      <el-table-column fixed="right" :label="t('common.operation')" width="250">
        <template #default="{ row }">
          <el-button @click="handleEdit(row)" size="small">
            {{ t('common.edit_t') }}
          </el-button>
          <el-button @click="handleDetail(row)" size="small" type="success">
            {{ t('action.detail') }}
          </el-button>
          <el-button @click="handleDelete('single', row)" size="small" type="danger">
            {{ t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
    <!--    新增/编辑弹框-->
    <Add ref="dialogarticleRef" @refresh="initialize" />
  </ContentWrap>
</template>

<script setup lang="ts">
import Add from './components/add.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { getarticleListApi, getarticleDelApi, getEnumApi } from '@/api/article'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])

const dialogarticleRef = ref()

const paginationTotal = ref<number>(0)

// 修改点1：新增createDateRange字段
const form = ref<Record<string, any>>({
  title: '',
  pageIndex: 1,
  pageSize: 20,
  create_time: '' // 日期范围数组（格式：["2025-07-01", "2025-07-15"]）
})

const categoryList = ref<Array<Record<string, any>>>([])
const typeList = ref<Array<Record<string, any>>>([])
//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  console.log(resp)
  categoryList.value = resp.data.category
  typeList.value = resp.data.type
}
//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}
//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
//点击新增
const handleAdd = () => {
  nextTick(() => {
    dialogarticleRef.value.getBackShow('add')
    dialogarticleRef.value.dialogVisible = true
  })
}
//点击编辑
const handleEdit = (row: Record<string, any>) => {
  nextTick(() => {
    dialogarticleRef.value.getBackShow('edit', JSON.parse(JSON.stringify(row)))
    dialogarticleRef.value.dialogVisible = true
  })
}

//点击详情
const handleDetail = (row: Record<string, any>) => {
  nextTick(() => {
    dialogarticleRef.value.getBackShow('detail', JSON.parse(JSON.stringify(row)))
    dialogarticleRef.value.dialogVisible = true
  })
}
//点击删除
const handleDelete = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('article.confirmDelete'), t('common.tip'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      // 这里需要替换为实际的员工删除API
      await getarticleDelApi({
        ids:
          type === 'single'
            ? [row.id]
            : multipleSelection.value.map((item: Record<string, any>) => item.id)
      })
      ElMessage.success(t('article.deleteSuccess'))
      await initialize()
    })
    .catch(() => {})
}

//初始化请求
const initialize = async () => {
  try {
    tableLoading.value = true

    // 修改点2：处理日期范围参数（逗号分隔格式）
    const params = {
      ...form.value
    }

    // 这里需要替换为实际的员工信息获取API
    const resp = await getarticleListApi(params)
    getDropDownBoxInfo()
    console.log(resp)
    dataList.value = resp.data.list
    paginationTotal.value = resp.data.total
    tableLoading.value = false
  } catch (e) {
    tableLoading.value = false
  }
}

//重置查询项
const reset = () => {
  // 修改点3：重置时包含createDateRange
  form.value = {
    title: '',
    pageIndex: 1,
    pageSize: 20,
    create_time: '' // 重置为空数组
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  initialize()
})
</script>

<style lang="less" scoped>
.m-1 {
  margin: 2px;
}
</style>
